/*
 * @Author: WangGuojian 1085844536@qq.com
 * @Date: 2022-09-20 15:31:46
 * @LastEditTime: 2022-09-20 15:37:02
 * @LastEditors: WangGuojian 1085844536@qq.com
 * @FilePath: \pro05-demo-all-in-one\src\main\java\com\atguigu\imperial\court\filter\LoginFilter.java
 * @Description:
 */
package com.atguigu.imperial.court.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.atguigu.imperial.court.util.ImperialCourtConst;

public class LoginFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        // 1.获取 HttpSession 对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpSession session = request.getSession();

        // 2.尝试从 Session 域获取已登陆的对象
        Object loginEmp = session.getAttribute(ImperialCourtConst.LOGIN_EMP_ATTR_NAME);

        // 3.判断 loginEmp 是否为空
        if (loginEmp != null) {

            // 4.若不为空则说明当前请求已登陆,直接放行
            filterChain.doFilter(request, servletResponse);

            return;
        }

        // 5.若为空说明尚未登陆,则回到登陆页面
        request.setAttribute("systemMessage", ImperialCourtConst.ACCESS_DENIED_MESSAGE);
        request.getRequestDispatcher("/").forward(request, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

}
